// pages/project/project.js
import api from '../../utils/api.js'
var app = getApp();
import { HTTP } from '../../utils/http.js'
import { config } from '../../utils/config'
let http = new HTTP()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        windowHeight: app.globalData.windowHeight,
        project: "", // 该专题的一些信息
        toView: "l1", // 顶部导航的定位
        page: 1, // 留言的当前页码
        size: 100, // 每页展示留言的数量
        content: "", // 评论输入框里面的内容
        // tuijianList: [], // 推荐菜谱的单品集合
        infoList: [], // 留言列表
        focus: false, // 是否通过点击回复获取
        flag: false, // 输入框是否获取焦点
        hide_good_box: true, // 小球的显示和隐藏
        white: app.globalData.white,
        id: 0,
        imgUrl: config.imgUrl,
    },
    // 接口
    // 集合型专题接口
    getProjectProduct(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.getProjectProduct,
                data: obj,
                success: res => {
                    this.setData({
                        project: res.data,
                        id: res.data.id
                    })
                    wx.setNavigationBarTitle({
                        title: res.data.name,
                    })
                    resolve(res.data);
                }
            })
        })
    },
    // 根据单品ID拿到相关分类的菜谱如果无则返回单品列表接口
    getCooksProducts(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.getCooksProducts,
                data: obj,
                success: res => {
                    resolve(res);
                }
            })
        })
    },
    //获得集合专题所有相关留言接口
    getProjectInfo(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.getProjectInfo,
                data: obj,
                success: res => {
                    resolve(res.data);
                }
            })
        })
    },
    //对专题留言的点赞接口
    addAttention(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.addAttention,
                data: obj,
                success: res => {
                    resolve(res)
                }
            })
        })
    },
    //对集合专题发表评论接口
    addProjectsInfo(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.addProjectsInfo,
                data: obj,
                success: res => {
                    var infoList = this.data.infoList
                    if (this.data.focus) {
                        wx.showToast({
                            title: '回复成功',
                        })
                        let id = this.data.parent_id
                        let infoList = this.data.infoList
                        let info = infoList.filter(item => {
                            return item.id == id
                        })[0]
                        var info1 = {
                            attention: 0,
                            classes: res.data.classes,
                            client_id: res.data.client_id,
                            content: res.data.content,
                            create_time: res.data.create_time,
                            id: res.data.id,
                            parent_id: [],
                            project_id: res.data.project_id,
                            users: {
                                id: wx.getStorageSync("user_id"),
                                clientavatar: wx.getStorageSync("avatarUrl"),
                                nickname: wx.getStorageSync("nickName")
                            },
                        }
                        info.parent_id.unshift(info1)
                    } else {
                        wx.showToast({
                            title: '评论成功',
                        })
                        var info = {
                            attention: 0,
                            classes: res.data.classes,
                            client_id: res.data.client_id,
                            content: res.data.content,
                            create_time: res.data.create_time,
                            id: res.data.id,
                            parent_id: [],
                            project_id: res.data.project_id,
                            users: {
                                id: wx.getStorageSync("user_id"),
                                clientavatar: wx.getStorageSync("avatarUrl"),
                                nickname: wx.getStorageSync("nickName")
                            },
                            show: false,
                            is_check: 0,
                        }
                        infoList.unshift(info)
                    }
                    console.log(infoList)
                    this.setData({
                        content: "",
                        focus: false,
                        infoList
                    })
                }
            })
        })
    },
    //获得单个留言及相关所有子留言接口
    getProjectSonInfo(obj) {
        http.request({
            url: api.getProjectSonInfo,
            data: obj,
            success: res => {
                console.log(res)
            }
        })
    },
    //判断该用户是否点赞一条留言接口
    sureInfo(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.sureInfo,
                data: obj,
                success: res => {
                    resolve(res.message);
                }
            })
        })
    },
    //判断用户是否关注专题接口
    getCollectStatus(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.getCollectStatus,
                data: obj,
                success: res => {
                    resolve(res)
                }
            })
        })
    },
    //用户对专题添加或取消收藏专题接口
    addDelCollectProject(obj) {
        http.request({
            url: api.addDelCollectProject,
            data: obj,
            success: res => {
                console.log(res)
            }
        })
    },
    // 单品加入菜篮接口
    shopping_cart_add(obj) {
        http.request({
            url: api.shoppingCartAdd,
            data: obj,
            success: res => {
                console.log(res)
                if (res.code == 200) {
                    wx.showToast({
                        title: '商品加入菜篮',
                        duration: 1500
                    })
                };
            }
        })
    },
    // 获取所有推荐菜谱和商品的列表
    getProduct(project_id) {
        this.getProjectProduct({ id: project_id, lng: wx.getStorageSync("address").longitude, lat: wx.getStorageSync("address").latitude, }).then(res => {
            var project = res
            console.log(res.class[0])
            this.getCollectStatus({ userId: wx.getStorageSync("user_id"), productId: project_id }).then(res => {
                if (res.message == "商品已经收藏了") {
                    project.flag = true
                } else {
                    project.flag = false
                }
                this.setData({
                    project
                })
            })
        })
    },
    getInfo(project_id) {
        let obj = {
            id: project_id,
            page: this.data.page,
            size: this.data.size
        }
        this.getProjectInfo(obj).then(res => {
            if (res) {
                var infoList = res.reverse()
                infoList.map((item, index) => {
                    item.show = false
                    this.sureInfo({
                        id: item.id,
                        uid: wx.getStorageSync("user_id"),
                    }).then(res => {
                        if (res == "该用户以点赞这条留言") {
                            item.is_check = 1
                        }
                        if (index == infoList.length - 1) {
                            console.log(infoList)
                            this.setData({
                                infoList
                            })
                        }
                    })
                })
            } else {
                this.setData({
                    infoList: []
                })
            }

        })
    },
    //单位的转化
    zhuanghua(goods) {
        goods.map((item) => {
            if (item.unit == 0) {
                item.unit = "kg"
            } else if (item.unit == 1) {
                item.unit = "份"
            } else if (item.unit == 2) {
                item.unit = "箱"
            } else if (item.unit == 3) {
                item.unit = "包"
            } else if (item.unit == 4) {
                item.unit = "袋"
            }
        })
    },
    // 获取评论输入框里面的内容
    write(e) {
        this.setData({
            content: e.detail.value
        })
    },
    // 回车发送评论
    send() {
        console.log(this.data.focus)
        if (!this.data.content) {
            return false
        }
        let obj = {
            parent_id: this.data.focus ? this.data.parent_id : 0,
            content: this.data.content,
            client_id: wx.getStorageSync("user_id"),
            project_id: this.data.project_id,
            classes: 0
        }
        this.addProjectsInfo(obj)
    },
    // 点击回复评论按钮
    reply(e) {
        var focus = this.data.focus
        focus = !focus
        this.setData({
            focus,
            parent_id: e.currentTarget.dataset.id
        })
    },
    // 评论输入框获取焦点
    focus(e) {
        this.setData({
            flag: true,
        })
    },
    // 评论输入框失去焦点
    blur() {
        setTimeout(() => {
            this.setData({
                flag: false,
                content: "",
                focus: false,
            })
        }, 300)
    },
    // 给评论点赞
    like(e) {
        let id = e.currentTarget.dataset.id
        let infoList = this.data.infoList
        let info = infoList.filter(item => {
            return item.id == id
        })[0]
        let statusID = 1
        if (!info.is_check) {
            info.is_check = 1
            info.attention++
        } else {
            info.is_check = 0
            info.attention--
            statusID = 2
        }
        let obj = {
            id,
            project_id: this.data.project_id,
            uid: wx.getStorageSync("user_id"),
            statusID
        }
        this.addAttention(obj)
        this.setData({
            infoList
        })
    },
    // 计数
    count() {
        var newList = wx.getStorageSync("select-menus") || []
        newList.filter((item) => {
            return item.num
        })
        var count = 0
        newList.map((item) => {
            count += item.num
        })
        this.setData({
            num: count
        })
    },
    // 点击添加菜谱
    add(e) {
        if (e.currentTarget.dataset.status == 1) {
            wx.showToast({
                title: '您附近暂时未上架该菜谱的相关食材!',
                icon: "none",
            })
            return
        }
        var that = this
        var listMenus = wx.getStorageSync('select-menus') || [];
        for (let v of listMenus) {
            if (v.id == e.target.dataset.id) {
                wx.showToast({
                    title: '请不要重复添加',
                    icon: 'none',
                    duration: 1500
                })
                return false;
            }
        }
        listMenus.push({
            flag: true,
            id: e.target.dataset.id,
            name: e.target.dataset.name,
            main_img_url: e.target.dataset.img,
            ingredients: [],
            count: e.target.dataset.count,
            time: e.target.dataset.time,
            seasoning_count: e.target.dataset.seasoning_count,
            num: 1
        });
        wx.setStorageSync("select-menus", listMenus);
        wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1500
        })
        this.count()
    },
    toMain(e) {
        if (this.data.num == 0) {
            wx.showToast({
                title: '您还未选菜',
                icon: "none"
            })
        } else {
            wx.navigateTo({
                url: "/pages/recommendShopList/recommendShopList?type=1"
            })
        }
    },
    // 点击添加单品
    add2(e) {
        if (!app.globalData.has) {
            wx.showToast({
                title: '您附近暂时没有接入商家，不能加入菜篮',
                icon: "none"
            })
            return false
        }
        let obj = {
            user_id: wx.getStorageSync("user_id"),
            product_id: e.target.dataset.id,
            summary: e.target.dataset.summary,
        }
        this.shopping_cart_add(obj)
    },
    // 点击展开更多评论
    more(e) {
        let id = e.currentTarget.dataset.id
        let infoList = this.data.infoList
        let info = infoList.filter(item => {
            return item.id == id
        })[0]
        info.show = true
        this.setData({
            infoList
        })
    },
    // 切换顶部导航
    change(e) {
        var id = e.currentTarget.dataset.id
        this.setData({
            toView: id
        })
    },
    //去菜谱详情页面
    toVideo(e) {
        var id = e.currentTarget.dataset.id
        console.log(id)
        wx.navigateTo({
            url: "/pages/video/video?id=" + id
        })
    },
    toDetail(e) {
        var id = e.target.dataset.id
        wx.navigateTo({
            url: "/pages/detail/detail?id=" + id
        })
    },
    // 关注和取消关注专题
    attention() {
        var project = this.data.project
        let obj = {
            userId: wx.getStorageSync("user_id"),
            productId: project.id
        }
        if (project.flag) {
            obj.statusID = 2;
            this.addDelCollectProject(obj);
            wx.showToast({
                title: '取消关注',
                icon: "none",
            })
        } else {
            obj.statusID = 1;
            this.addDelCollectProject(obj);
            wx.showToast({
                title: '关注成功',
            })
        }
        project.flag = !project.flag
        this.setData({
            project
        })
    },
    // 点击查看更多按钮
    lookMore(e) {
        var moreList = this.data.project.class[0].filter(item => {
            return item.classes_id == e.currentTarget.dataset.id
        })[0].classx.type
        var title = this.data.project.class[0].filter(item => {
            return item.classes_id == e.currentTarget.dataset.id
        })[0].classx.name
        wx.navigateTo({
            url: '/pages/more/more?moreList=' + JSON.stringify(moreList) + '&title=' + JSON.stringify(title),
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.count() // 获取已选菜单里面的数量
        var project_id = options.id || 31
        this.setData({
            project_id
        })
        this.getProduct(project_id) // 获取所有推荐菜谱和商品的列表
        this.getInfo(project_id) // 获取所有留言
        var query = wx.createSelectorQuery();
        console.log(query)
        query.select(".box").boundingClientRect(function (rect) {
            console.log(rect)
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    // 分享
    onShareAppMessage: function (res) {
        let lng = wx.getStorageSync('address').longitude
        let lat = wx.getStorageSync('address').latitude
        return {
            path: `/pages/index/index?redirect=/pages/project/project&typeShare=1&id=${this.data.id}&lng=${lng}&lat=${lat}`,
        }
    }
})